package com.xtkj.superclub_tourpal.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xtkj.commons.JsonResult;
import com.xtkj.commons.SnowflakeIdWorker;
import com.xtkj.superclub_entity.entity.tourpal.Team;
import com.xtkj.superclub_entity.entity.tourpal.TeamRole;
import com.xtkj.superclub_entity.entity.tourpal.TeamRoleUser;
import com.xtkj.superclub_entity.entity.tourpal.UserTeam;
import com.xtkj.superclub_entity.entity.user.User;
import com.xtkj.superclub_tourpal.dao.*;
import com.xtkj.superclub_tourpal.service.ITourpalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class TourpalServiceImpl implements ITourpalService {
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ITourpalUserDao tourpalUserDao;
    @Autowired
    private ITourpalTeamDao tourpalTeamDao;
    @Autowired
    private ITourpalUserTeamDao tourpalUserTeamDao;
    @Autowired
    private ITourpalTeamRoleUserDao tourpalTeamRoleUserDao;
    @Autowired
    private ITourpalTeamRoleDao tourpalTeamRoleDao;


    /**
     * @param userId
     * @return java.util.List<com.xtkj.superclub_entity.entity.tourpal.Team>
     * @description 方法描述
     * 根据用户查询用户所在的队伍编号
     * 根据查询出来的队伍编号查询队伍列表信息
     * @author xiezhiyan
     * @date 2019/12/25 14:21
     */
    @Override
    public List<Team> getTourPal(String userId) {
        // TODO: 2019/12/25 根据用户查询用户所在的队伍编号列表
        QueryWrapper wrapper = new QueryWrapper<>().select("team_id").eq("user_id", userId);
        // TODO: 2019/12/25 根据查询出来的队伍编号查询队伍列表信息
        return tourpalTeamDao.selectBatchIds(tourpalUserTeamDao.selectObjs(wrapper));
    }


    /**
     * @param team
     * @return boolean
     * @description 方法描述
     * 创建驴友队审核通过后创建队伍，相册，队伍
     * @author xiezhiyan
     * @date 2019/12/25 16:24
     */
    @Override
    public void createTourPal(String userId, Team team) {
        // TODO: 2019/12/25 根据用户查询用户所在的队伍编号
        //设置队伍id，队伍相册id,游记id,
        String teamId = snowflakeIdWorker.nextId() + "";
        //设置相册id
        String teamAlbumId = snowflakeIdWorker.nextId() + "";
        // TODO: 2019/12/28  审核通过后(调用其他接口)
        //创建相册
        tourpalTeamDao.insert(team.setTeamId(teamId).setTeamAlbumId(teamAlbumId));
        //创建用户队伍记录
        tourpalUserTeamDao.insert(new UserTeam().setUserId(userId).setTeamId(teamId));
        //创建用户队伍角色记录(队长身份)
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(new QueryWrapper<TeamRole>().eq("team_role_name", "队长"));
        tourpalTeamRoleUserDao.insert(new TeamRoleUser().setCreatedtm(new Date()).setUpdatedtm(new Date()).setUserId(userId).setUserTeamId(teamId).setTeamRoleId(teamRole.getTeamRoleId()));
    }


    /**
     * @param addInfo
     * @return boolean
     * @description 方法描述
     * 加入前，根据队伍id或名称查询所有队伍信息
     * @author xiezhiyan
     * @date 2019/12/25 17:02
     */
    @Override
    public List<Team> preAddTourPal(String addInfo) {
        //根据队伍id或名称查询队伍是否存在，查出相关的俱乐部列表
        QueryWrapper<Team> wrapper = new QueryWrapper<Team>().eq("team_id", addInfo).or().like("team_name", addInfo);
        return tourpalTeamDao.selectList(wrapper);
    }

    /**
     * @param userId
     * @param teamId
     * @return com.xtkj.commons.JsonResult
     * @description 方法描述
     * 加入驴友队,添加到用户队伍表，用户队伍角色表(成员)，
     * @author xiezhiyan
     * @date 2019/12/28 17:07
     */
    @Override
    public void addTourPal(String userId, String teamId) {
        //插入用户队伍信息
        tourpalUserTeamDao.insert(new UserTeam(userId, teamId));
        //插入用户队伍角色表
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(new QueryWrapper<TeamRole>().eq("team_role_name", "成员"));
        tourpalTeamRoleUserDao.insert(new TeamRoleUser().setUserId(userId).setUserTeamId(teamId).setTeamRoleId(teamRole.getTeamRoleId()).setUpdatedtm(new Date()).setCreatedtm(new Date()));
    }

    /**
     * @param userId,teamId
     * @return void
     * @description 方法描述
     * 退出驴友队,从用户队伍表中删除该用户,删除用户队伍角色信息
     * @author xiezhiyan
     * @date 2019/12/27 9:34
     */
    @Override
    public JsonResult outTourPal(String userId, String teamId) {
        //从用户队伍表中删除该用户
        UpdateWrapper<UserTeam> wrapper = new UpdateWrapper<UserTeam>().eq("user_id", userId).eq("team_id", teamId);
        tourpalUserTeamDao.delete(wrapper);
        // TODO: 2019/12/27 查询该用户的角色，删除用户队伍角色信息
        UpdateWrapper<TeamRoleUser> teamRoleUserQueryWrapper = new UpdateWrapper<TeamRoleUser>().eq("user_id", userId).eq("user_team_id", teamId);
        tourpalTeamRoleUserDao.delete(teamRoleUserQueryWrapper);

        List<TeamRoleUser> teamRoleUserList = tourpalTeamRoleUserDao.selectList(teamRoleUserQueryWrapper);
        if (CollectionUtils.isEmpty(teamRoleUserList)) {
            return JsonResult.success().setMsg("删除用户队伍成功").setCode(200);
        }
        tourpalTeamRoleUserDao.deleteById(userId);
        return JsonResult.success().setMsg("删除用户队伍和用户队伍角色成功").setCode(500);
    }

    /**
     * @param userId
     * @param teamId
     * @return com.xtkj.commons.JsonResult
     * @description 方法描述
     * 查询本俱乐部是否有副队长，如果没有副队长，返回成员列表，如果有返回副队长只能设置一名
     * @author xiezhiyan
     * @date 2019/12/28 21:19
     */
    @Override
    public JsonResult preAppointViceCaptain(String userId, String teamId) {
        //查询副队长角色id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "副队长");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);
        //查询本俱乐部是否有副队长，如果没有副队长，返回成员列表，如果有返回副队长只能设置一名
        QueryWrapper queryWrapper = new QueryWrapper<>().eq("user_team_id", teamId).eq("team_role_id",teamRole.getTeamRoleId());
        TeamRoleUser teamRoleUser = tourpalTeamRoleUserDao.selectOne(queryWrapper);
        if (Objects.nonNull(teamRoleUser)) {
            return JsonResult.error().setCode(500).setMsg("无法设置，副队长只能设置一名");
        }
        //查询所有管理员,成员列表
        //查询管理员,成员角色id列表
        QueryWrapper wrapperListRoleId = new QueryWrapper<>().select("team_role_id").in("team_role_name", "成员", "管理员");
        List<String> roleIdlist = tourpalTeamRoleDao.selectObjs(wrapperListRoleId);
        //查询员工id列表
        QueryWrapper wrapperUserIdList = new QueryWrapper<>().select("user_id").eq("user_team_id", teamId).in("team_role_id", roleIdlist);
        List<String> userIdList = tourpalTeamRoleUserDao.selectObjs(wrapperUserIdList);
        //查询员工列表
        List<User> users = tourpalUserDao.selectBatchIds(userIdList);
        return JsonResult.success().setMsg("可授予副队长的用户列表").setCode(200).setData(users);
    }

    /**
     * @param teamId
     * @param AppointedUserId
     * @return com.xtkj.commons.JsonResult
     * @description 方法描述
     * 任命副队长
     * @author xiezhiyan
     * @date 2019/12/29 15:23
     */
    @Override
    public void appointViceCaptain(String teamId, String AppointedUserId) {
        //查询副队长id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "副队长");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);

        TeamRoleUser teamRoleUser = tourpalTeamRoleUserDao.selectOne(new QueryWrapper<TeamRoleUser>().eq("user_id", AppointedUserId).eq("user_team_id", teamId));
        UpdateWrapper wrapper1 = new UpdateWrapper<>().set("team_role_id", teamRole.getTeamRoleId()).eq("user_team_id",teamId).eq("user_id",AppointedUserId);
        tourpalTeamRoleUserDao.update(teamRoleUser,wrapper1);
    }

    /**
     * @param userId
     * @param teamId
     * @return com.xtkj.commons.JsonResult
     * @description 方法描述
     * 取消前先查询副队长列表
     * @author xiezhiyan
     * @date 2019/12/29 14:56
     */
    @Override
    public JsonResult preCancelViceCaptain(String userId, String teamId) {
        //查询副队长id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "副队长");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);
        QueryWrapper<TeamRoleUser> queryWrapper = new QueryWrapper<TeamRoleUser>().eq("user_team_id", teamId).eq("team_role_id", teamRole.getTeamRoleId());
        TeamRoleUser teamRoleUser = tourpalTeamRoleUserDao.selectOne(queryWrapper);
        if (Objects.isNull(teamRoleUser)) {
            return JsonResult.error().setCode(500).setMsg("没有副队长可以被取消");
        }
        //返回副队长成员
        User user = tourpalUserDao.selectById(teamRoleUser.getUserId());
        return JsonResult.success().setMsg("可以被取消的副队长人员").setData(user);
    }

    /**
     * @param canceledUserId
     * @param teamId
     * @return com.xtkj.commons.JsonResult
     * @description 方法描述
     * 取消副队长，将用户队伍角色表中副队长记录修改为成员角色，
     * @author xiezhiyan
     * @date 2019/12/28 12:30
     */
    @Override
    public void cancelViceCaptain(String canceledUserId, String teamId) {
        //查询成员id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "成员");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);
        String teamMemberRoleId = teamRole.getTeamRoleId();
        //获取该成员记录
        TeamRoleUser canceledTeamRoleUser = tourpalTeamRoleUserDao.selectOne(new QueryWrapper<TeamRoleUser>().eq("user_id", canceledUserId).eq("user_team_id", teamId));
        UpdateWrapper<TeamRoleUser> updateWrapper = new UpdateWrapper<TeamRoleUser>().set("team_role_id", teamMemberRoleId).eq("user_id",canceledUserId).eq("user_team_id",teamId);
        //修改该成员记录,更新为副队长
        tourpalTeamRoleUserDao.update(canceledTeamRoleUser, updateWrapper);
    }

    /**
     * @param userId
     * @param teamId
     * @return com.xtkj.commons.JsonResult
     * @description 方法描述
     * 查询可以任命管理员的成员列表
     * @author xiezhiyan
     * @date 2019/12/30 10:05
     */
    @Override
    public JsonResult preAppointLeader(String userId, String teamId) {
        //查询成员角色id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "成员");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);
        //查询成员id列表
        QueryWrapper wrapperUserIdLis = new QueryWrapper<>().select("user_id").eq("user_team_id", teamId).eq("team_role_id", teamRole.getTeamRoleId());
        List<String> userIdList = tourpalTeamRoleUserDao.selectObjs(wrapperUserIdLis);
        if (CollectionUtils.isEmpty(userIdList)){
            return JsonResult.error().setCode(500).setMsg("无可以任命的成员");
        }else {
            //查询成员列表
            List<User> userList = tourpalUserDao.selectBatchIds(userIdList);
            return JsonResult.success().setCode(200).setMsg("查询成员列表成功").setData(userList);
        }
    }

    @Override
    public JsonResult appointLeader(String appointedLeaderUserId, String teamId) {
        //查询管理员角色id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "管理员");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);
        //首先查询管理员人数，不能大于等于8
        QueryWrapper wrapperCount = new QueryWrapper<>().eq("user_team_id", teamId).eq("team_role_id", teamRole.getTeamRoleId());
        Integer userCount = tourpalTeamRoleUserDao.selectCount(wrapperCount);
        if (8 == userCount) {
            return JsonResult.error().setCode(500).setMsg("管理员数量不能超过8名");
        } else {
            //查询该成员的角色信息
            QueryWrapper<TeamRoleUser> teamRoleUserQueryWrapper = new QueryWrapper<TeamRoleUser>().eq("user_team_id", teamId).eq("user_id", appointedLeaderUserId);
            TeamRoleUser teamRoleUser = tourpalTeamRoleUserDao.selectOne(teamRoleUserQueryWrapper);
            //更新它的角色为管理员
            UpdateWrapper<TeamRoleUser> userUpdateWrapper = new UpdateWrapper<TeamRoleUser>().set("team_role_id", teamRole.getTeamRoleId()).eq("user_id",appointedLeaderUserId).eq("user_team_id",teamId);
            tourpalTeamRoleUserDao.update(teamRoleUser, userUpdateWrapper);
            return JsonResult.error().setCode(500).setMsg("任命管理员成功");
        }
    }

   /**
    * @description 方法描述
    * 查询可转让队长的成员列表
    * @param userId
    * @param teamId
    * @return com.xtkj.commons.JsonResult
    * @author xiezhiyan
    * @date 2019/12/30 11:36
    */

   @Override
    public  JsonResult preAssignmentTourPal(String userId, String teamId) {
        //查询队长角色id
        QueryWrapper<TeamRole> wrapper = new QueryWrapper<TeamRole>().eq("team_role_name", "队长");
        TeamRole teamRole = tourpalTeamRoleDao.selectOne(wrapper);
        //查询除了队长之外的id列表
        QueryWrapper WrapperUserIdList = new QueryWrapper<>()
                .select("user_id")
                .ne("team_role_id", teamRole.getTeamRoleId())
                .eq("user_team_id", teamId);
        List<String> userIdList = tourpalTeamRoleUserDao.selectObjs(WrapperUserIdList);
        if(CollectionUtils.isEmpty(userIdList)){
            return JsonResult.error().setCode(500).setMsg("无可以转让的人选");
        }else {
            //查询成员列表
            List<User> users = tourpalUserDao.selectBatchIds(userIdList);
            return JsonResult.success().setCode(200).setMsg("可以转让队长的成员列表").setData(users);
        }
    }

    /**
     * @description 方法描述
     * 将队长身份设置为成员，被转让的成员角色变为队长
     * @param assignmentedUserId
     * @param teamId
     * @return com.xtkj.commons.JsonResult
     * @author xiezhiyan
     * @date 2019/12/30 12:29
     */
    @Override
    public void assignmentTourPal(String userId,String assignmentedUserId, String teamId) {
       //查询队长角色id
        QueryWrapper<TeamRole> wrapperCaptain = new QueryWrapper<TeamRole>().eq("team_role_name", "队长");
        TeamRole captain = tourpalTeamRoleDao.selectOne(wrapperCaptain);
        //查询成员角色id
        QueryWrapper<TeamRole> wrapperMember = new QueryWrapper<TeamRole>().eq("team_role_name", "成员");
        TeamRole member = tourpalTeamRoleDao.selectOne(wrapperMember);
        System.out.println();
        //查询队伍信息
        Team team = tourpalTeamDao.selectById(teamId);
        //查询该成员信息
        TeamRoleUser captainTeamRoleUser = tourpalTeamRoleUserDao.selectOne(new QueryWrapper<TeamRoleUser>().eq("user_id", userId).eq("user_team_id", teamId));
        System.out.println(captainTeamRoleUser);
        TeamRoleUser memberTeamRoleUser= tourpalTeamRoleUserDao.selectOne(new QueryWrapper<TeamRoleUser>().eq("user_id",assignmentedUserId).eq("user_team_id",teamId));
        System.out.println(memberTeamRoleUser);
        //更新角色信息
        tourpalTeamRoleUserDao.update(captainTeamRoleUser,new UpdateWrapper<TeamRoleUser>().set("team_role_id",member.getTeamRoleId()).eq("user_id",captainTeamRoleUser.getUserId()).eq("user_team_id",teamId));
        tourpalTeamRoleUserDao.update(memberTeamRoleUser,new UpdateWrapper<TeamRoleUser>().set("team_role_id",captain.getTeamRoleId()).eq("user_id",memberTeamRoleUser.getUserId()).eq("user_team_id",teamId));
        //更新队伍表中负责人id
        tourpalTeamDao.update(team,new UpdateWrapper<Team>().set("user_id",memberTeamRoleUser.getUserId()).eq("team_id",teamId));
    }


    

}

